import { onMounted, reactive } from 'vue';
import { Access, accessService } from '@/services/authorization/Access';
import { HttpUtil } from '@/utils/HttpUtil';
import { ElMessage } from 'element-plus';
import { nest } from '@/utils/TreeNode';

export interface AuthorityNode extends Access {
  children: AuthorityNode[];
}

export interface UseAuthority {
  roots: AuthorityNode[];
  select: () => Promise<void>;
}

export const useAuthority = (): UseAuthority => {
  const roots: AuthorityNode[] = reactive([] as AuthorityNode[]);

  const select = async () => {
    try {
      const resp = await accessService.selectAll();
      if (HttpUtil.isOk(resp)) {
        roots.splice(0, roots.length);
        nest<Access, string>(HttpUtil.getList(resp)).forEach(v => roots.push(v));
        // console.log(roots);
      }
    } catch (e) {
      ElMessage.error((e as Error).message);
    }
  };

  onMounted(select);

  return {
    roots,
    select,
  };
};
